package com.example.mqtt.config;

import jakarta.annotation.Resource;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;

/**
 * <pre>
 *     setCleanSession：
 *     true  每次以新的身份连接服务器
 *     false 服务器会保留客户端的连接记录，客户端掉线后服务器端不会清除session，当重连后可以接收之前订阅主题的消息，客户端上线后会接收到它离线的这段时间的消息
 * </pre>
 **/
@Configuration
public class MqttConfig {
    @Resource
    private MqttProperty mqttProperty;

    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        options.setServerURIs(mqttProperty.getUrl().split(","));// 多个url集群
        options.setUserName(mqttProperty.getUsername());
        options.setPassword(mqttProperty.getPassword().toCharArray());
        options.setAutomaticReconnect(true);

        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(options);
        return factory;
    }

}
